package com.study.sync;

/**
 * 资源类
 */
class Ticket {
    // 票数
    private int number = 30;
    // 操作方法：卖票
    public synchronized void sale() {
        // 判断是否有票
        if (number > 0) {
            System.out.println(Thread.currentThread().getName()+"：卖出："+(number--)+"，剩下："+number+" 张票");
        }
    }
}

/**
 * @author wanghao
 * @version v1.0
 * @description:
 * @date 2021/12/24 15:11
 * @change [修改时间] [修改者]@[版本号] [修改内容说明]
 */
public class SaleTicket {

    public static void main(String[] args) {

        Ticket ticket = new Ticket();

        // 创建多个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 循环调用卖票方法
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        },"AA").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        },"BB").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        },"CC").start();

    }

}
